# coding=utf-8
from flask_wtf import FlaskForm
from wtforms import fields, validators
from app_admin.models.admins import Admins as Users
from redis import Redis
from flask import current_app


class LoginForm(FlaskForm):
    phone = fields.StringField(u'手机', [validators.DataRequired(u'手机号不能为空')])
    password = fields.PasswordField(u'密码', [validators.DataRequired(u'密码不能为空')])
    sms_code = fields.StringField(u'验证码', [validators.DataRequired(u'验证码不能为空')])

    @property
    def user(self):
        return Users.query.filter_by(phone=self.phone.data).first()

    def validate_phone(self, field):
        if not self.user:
            raise validators.ValidationError(u'账户不存在')

    def validate_password(self, field):
        if self.user and not self.user.validate_password(field.data):
            raise validators.ValidationError(u'密码错误')

    def validate_sms_code(self, field):
        redis = Redis()
        code = redis.get('SMS_CODE_%s' % self.phone.data)

        if not current_app.debug:
            if not code or code != field.data:
                raise validators.ValidationError(u'验证码错误')
